package cn.middle.remote.handler.decodec;

import java.util.List;

import cn.middle.remote.message.LoginResultSignal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class LoginResultSignalCodec implements Codec<LoginResultSignal>{

	 private int mutableLength = 4 +  4 + 4;
	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		if(in.readableBytes() < mutableLength) {
			in.readerIndex(beginIndex);
			return ;
		}
		
		int msgIdLength = in.readInt();
		if(!CodecUtil.checkLength(in, msgIdLength + 4 + 4, beginIndex)) {
			return; 
		}
		
		String msgId = CodecUtil.context(in, msgIdLength);
		int code = in.readInt();
		int messageLength = in.readInt();
		if(!CodecUtil.checkLength(in, messageLength, beginIndex)) {
			return; 
		}
		String message = CodecUtil.context(in, messageLength);
		LoginResultSignal result = new LoginResultSignal();
		result.setId(msgId);
		result.setCode(code);
		result.setMessage(message);
		
		out.add(result);
	}
	
	

	@Override
	public void encode(ChannelHandlerContext ctx, LoginResultSignal msg, ByteBuf out) throws Exception {
		out.writeBytes(msg.toData());
	}

}
